﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AsPlugInManager;
using AsLib;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using System.Globalization;

namespace NNLInterface
{
    public partial class frmCalendarImport : NNLInterface.frmBaseBasic
    {
     
        #region 初始化

        string strSQLHead = " select cast(1 as bit) as chkSelect , * from vie_Calendar ";
        string strTranNo = "";
        private bool filterFormFlag;
        private System.Data.DataTable dt;

        public frmCalendarImport()
        {
            InitializeComponent();

        }

        public frmCalendarImport(IASPArgList argList)
        {
            InitializeComponent();
            common.agrs = (ASPArgList)argList;
            this.lokDepart.EditValueChanged += new EventHandler(lokDepart_EditValueChanged);
            this.lokDepart.ProcessNewValue += new DevExpress.XtraEditors.Controls.ProcessNewValueEventHandler(lokDepart_ProcessNewValue);

            this.ListGrid.MouseDown += new MouseEventHandler(ListGrid_MouseDown);
            this.repbuttonedit.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(repbuttonedit_ButtonClick);
        }

        void repbuttonedit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            SearchShiftData();
        }

        private void SearchShiftData()
        {
            string strSql = "SELECT a.Code,a.Patterns FROM shift a";
            this.Tag = "";
            frmNoteSearch frmSearch = new frmNoteSearch(this, "Shift", strSql, true);
            filterFormFlag = true;
            frmSearch.ShowDialog();
            if (this.Tag.ToString() != "")
            {
                //找出数据，显示在listview行中
                DataRow dt = (DataRow)this.Tag;
                ListView.SetRowCellValue(ListView.FocusedRowHandle, ListView.Columns["ShiftCode"], dt["Code"].ToString());
                ListView.SetRowCellValue(ListView.FocusedRowHandle, ListView.Columns["ShiftName"], dt["Patterns"].ToString());
                //ListView.FocusedColumn = ListView.VisibleColumns[ListView.Columns.Count - 1];
                ListView.ShowEditor();
                ListView.SetColumnError(ListView.Columns["ShiftCode"], "");
            }
            filterFormFlag = false;
        }

        void frmCalendarImport_Load(object sender, EventArgs e)
        {
            
            this.SowCheckBox = true;

            //如果当前工程下的用户名为空，则提示输入
            if (common._userid == "")
            {
                frmLogon frmLog = new frmLogon();
                frmLog.ShowDialog();

                if (frmLog.DialogResult == DialogResult.OK)
                {
                    frmLog.Dispose();
                    frmLog = null;
                }
                else
                {
                    this.Close();
                    return;
                }

            }

            IniDataSource();


        }


        private void IniDataSource()
        {
            //设定日期值
            this.dteFrom.EditValue=DateTime.Now;
            this.dteTo.EditValue = DateTime.Now.AddDays(common.sysParameter.IntervalDays);
            this.txtUser.Text = common._userid;
            this.txtUserName.Text = common._username;
            this.txtDeptNo.Text = common._DeptNo;
            this.txtDeptName.Text = common._DeptName;

            SetDeptDataSource();

            string strSQL = strSQLHead + " where 1=2";
            common.SubShowList(accessdb.GetRecord(strSQL).ADODataRst, this.ListGrid, this.ListView, false);
            common.subIniGrid(this.ListView, common.enumGridStyle.ViewStyle); 
            common.ReStoreLayOut(this.ListView);
            common.GetResourceString(this,this.ListView);
            common.RestoreFormLayOut(this, this.layOut, this.grpHead);
            this.ListView.Columns["ShiftCode"].ColumnEdit = this.repbuttonedit;
            this.SetToolVisible(common.ToolVisible.ImportData);
            this.logButtonVisibility = false;

        }
        #endregion

        private void SetDeptDataSource()
        {
            //如果是制5课计划，则部门直接是制5课的
            string strSQL = "SELECT DepartNo,DeptName FROM vie_SysUserDepartMent vsudm WHERE vsudm.UserId='" + this.txtUser.Text + "'";
            strSQL += " and   DepartNo not like '%5%'";

            this.lokDepart.Properties.DataSource = accessdb.GetRecord(strSQL).ADODataRst;
            this.lokDepart.Text = "";
            this.lokDepart.EditValue = null;



        }

        void lokDepart_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
            lookupeditProcess.LookUpEditProcessNewValue(sender, ref e);

        }

        void lokDepart_EditValueChanged(object sender, EventArgs e)
        {
            if (this.lokDepart.Text != "")
                this.txtDepartName.Text = this.lokDepart.GetColumnValue("DeptName").ToString();
            else
                this.txtDepartName.Text = "";
        }


        #region Grid选择按钮

        private void ListGrid_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
                DoShowMenu(this.ListView.CalcHitInfo(new Point(e.X, e.Y)));
        }

        void DoShowMenu(DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hi)
        {

            if (hi.HitTest == DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitTest.ColumnButton)
            {
                common.subSelectData(ListGrid, ListView);
            }
        }
        #endregion


        private void frmCalendarImport_ToolButtonClick(object sender, string e)
        {
            try
            {
                switch (e)
                {
                    case "search":
                        if(!GetDataFromERP()) return;
                        common.SubShowList(SearchData(), this.ListGrid, this.ListView, false);
                        common.subIniGrid(this.ListView,common.enumGridStyle.ViewStyle);
                        this.ListView.Columns["chkSelect"].OptionsColumn.AllowEdit = true;
                        this.ListView.Columns["ShiftCode"].OptionsColumn.AllowEdit = true;
                        this.ListView.Columns["ShiftCode"].OptionsColumn.ReadOnly = true;
                        this.ListView.Columns["SortOrder"].OptionsColumn.AllowEdit = true;
                        setGridFormat();
                        this.ListGrid.Tag = 1;
                        common.ReStoreLayOut(this.ListView);
                        break;
                    case "import":
                        subExportData();
                        break;
                    case "excel":
                        subExportXLS();
                        break;
                    case "print":
                        common.PrintView(this.ListGrid, "日历数据");
                        break;
                    case "exit":
                        common.SaveFormLayOut(this, this.layOut, this.grpHead);
                        common.SaveLayout(this.ListView);
                        this.Dispose();
                        break;
                    default:
                        {
                            break;
                        }
                }

                
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
           
        }

        private void setGridFormat()
        {



            this.ListView.Columns["SortOrder"].AppearanceHeader.ForeColor = Color.Red;
            this.ListView.Columns["ShiftCode"].AppearanceHeader.ForeColor = Color.Red;

            this.ListView.Columns["SortOrder"].AppearanceCell.BackColor = common.sysParameter.EditColumnBackColor;
            this.ListView.Columns["ShiftCode"].AppearanceCell.BackColor = common.sysParameter.EditColumnBackColor;
 


        }

        private bool GetDataFromERP()
        {
            try
            {
                //部门必须选择
                if (this.lokDepart.Text == "")
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("最终部门不能为空!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    lokDepart.Focus();
                    return false;
                }
                
                //起止日期必须输入
                if (this.dteFrom.Text=="")
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("起始日期不能为空!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    dteFrom.Focus();
                    return false;
                }

                if (this.dteTo.Text == "")
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("截止日期不能为空!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    dteTo.Focus();
                    return false;
                }
                
                //取得最大的批次号
                strTranNo = Convert.ToString(accessdb.GetField("SELECT   'CAL' + replace(dbo.GetShortDate(GETDATE()),'-','')"));
                strTranNo = Convert.ToString(accessdb.ExecuteSP("pro_GetMaxNoteNo", common.Choose.HasAOutput, new object[] { strTranNo, 3, "CalendarImport", strTranNo }));

                //根据查询条件从ERP中写入数据


                //根据条件取得数据
                DataTable dt = (DataTable)accessdb.ExecuteSP(common.strERPConnect,  "getDepValue", common.Choose.RetOneRecord, new object[] { this.dteFrom.Text, this.dteTo.Text });
                if (dt==null) return false;

                string strSQL = "  SET XACT_ABORT ON BEGIN TRAN";

                //将数据写临时表中
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //部门找到班次，缺省的班次
                    string strShiftCode="";
                    string strDeptNo = dt.Rows[i]["dep"].ToString().Substring(1, 1);
                    strShiftCode = (string)accessdb.GetField("SELECT bdm.ShiftNo FROM BasDepartMent bdm WHERE bdm.DeptNo LIKE '%" + strDeptNo + "%'");
                    strSQL += " INSERT INTO Calendar "
                          + "  (ResourceCode,Dates,ShiftCode,"
                          + "    DefaultQty,TranNo,EntUser,EntDate,CalendarUser_UMans "
                          + "  )"
                          + " values('"
                          + dt.Rows[i]["dep"].ToString() + "','"
                          + Convert.ToDateTime(dt.Rows[i]["RQ"]).ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo) + "','"
                          + strShiftCode + "',"
                          + Convert.ToDouble(dt.Rows[i]["value"]) + ",'"
                          + strTranNo + "','"
                          + common._userid + "',getdate(),"
                          + Convert.ToInt32(dt.Rows[i]["rs"]) + ")\r\n";
                     
                }
                strSQL += " commit tran";
                if (!accessdb.RsChange(strSQL)) return false;

                return true;
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void subPrint()
        {
            if (!common.CheckExistsData(this.ListView)) return;
            common.PrintView(this.ListGrid, "工作日历数据");
        }

        private void subExportXLS()
        {
            try
            {
                if (!common.CheckExistsData(this.ListView)) return;
                common.ExportExcel(this.ListView);
                return;
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
           
        }

        private DataTable SearchData()
        {
            dt = new DataTable();
            string strSQL = strSQLHead + "   where TranNo='" + strTranNo + "'";
            strSQL += " and ResourceCode like '%" + lokDepart.Text + "%'";
            dt = accessdb.GetRecord(strSQL).ADODataRst;
            return dt;
        }

        private void subExportData()
        {
            
            Cursor currentCursor = Cursor.Current;

            try
            {
                //common.UpdateListView(this.ListView);
                this.ListView.CloseEditor();
                this.ListView.UpdateCurrentRow();
                DataTable viewt = (DataTable)this.ListGrid.DataSource;
                DataRow[] drs = viewt.Select("chkSelect=1");

                if (!common.CheckExistsData(this.ListView)) return;
                if (!CheckReSource(drs)) return;
               
               
                if (drs.Length < 1)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("请至少选择一笔数据!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    if (DevExpress.XtraEditors.XtraMessageBox.Show("确定要将所选择数据导入Asprova中吗(Y/N)?", common.sysParameter.MessageInf, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) return;
                    Cursor.Current = Cursors.WaitCursor;


                    //取得当前的生产日历
                    AsLib.ASBCalendar calendar = common.pro.RootCalendar;
                    string calSource="";
                    string calDate = "";
                    string drsSource = "";
                    int dateCount = 0;
                    ASBResource resource;
                    ASVDateExpression calNewDate;
                    string stritemid = "";
                    string drsDate = "";


                    bool flag=false;  //是否在Asprova中已存在相同的工作日历
                   
                    for (int row = 0; row < drs.Length; row++)
                    {
                        flag = false;
                        drsSource = drs[row]["ResourceCode"].ToString().Trim();
                        drsDate = Convert.ToDateTime(drs[row]["Dates"].ToString()).ToString("yyyy/MM/dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
                        if (calendar.ChildCount>=1)
                        {
                            for (int i = 0; i < calendar.ChildCount; i++)
                            {
                                //如果当前的日期值是一个独立一的日期值，则如果资源编相同，且日期值相同，则更新
                                calSource = calendar.get_ChildAsCalendar(i).get_Resource(0).Code.Trim();
                                calDate = calendar.get_ChildAsCalendar(i).get_Date(0).GetStr().Trim();
                                dateCount = calendar.get_ChildAsCalendar(i).DateCount;
                                if (dateCount == 1 && common.IsDateTime(calDate))
                                {
                                    string strComment=calendar.get_ChildAsCalendar(i).get_Comment(0)==null?"":calendar.get_ChildAsCalendar(i).get_Comment(0).ToString();
                                    if (drsSource == calSource && drsDate == Convert.ToDateTime(calDate).ToString("yyyy/MM/dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo) && strComment.IndexOf("ERP导入") >= 0)
                                    {
                                        //更新实际人数(ERP中的RS是实际人数,VALUE是资源量）
                                        calendar.get_ChildAsCalendar(i).SetAsStr((TPropertyID)Convert.ToInt32(common.GetLanguageWord("PropertyID", "CalendarUser_UMans")), 1, drs[row]["CalendarUser_UMans"].ToString());
                                        //更新班次
                                        calendar.get_ChildAsCalendar(i).SetAsStr((TPropertyID)Convert.ToInt32(common.GetLanguageWord("PropertyID", "Cal_ShiftCode")), 1, drs[row]["ShiftCode"].ToString());
                                        //更新资源量
                                        calendar.DefaultQty =Convert.ToDouble(drs[row]["DefaultQty"]) ;

                                        flag = true;
                                        break;
                                    }
                                }

                            }
                        }
                        if(!flag) //如果不存在，则写入新的工作日历列表中
                        {
                            
                           stritemid += drs[row]["itemid"].ToString() + ",";
                            
                        }
                    }

                    common.pro.UpdateAll();

                   //添加工作日历
                    if (stritemid!="")
                    {
                        stritemid = stritemid.Substring(0, stritemid.Length - 1);
                        //string strSQL = "SELECT * FROM Calendar c WHERE c.ItemID IN (" + stritemid + ")";
                        //DataTable  dt=accessdb.GetRecord(strSQL).ADODataRst;
                        DataTable dt = ((DataView)ListView.DataSource).Table;
                        DataRow[] dr = dt.Select("ItemID IN (" + stritemid + ")");
                        for (int row= 0; row< dr.Length; row++)
                        {
                            AsLib.ASBCalendar calendarNew = new ASBCalendar();
                            drsSource = dr[row]["ResourceCode"].ToString();
                            resource = (ASBResource)common.pro.RootResource.FindChild(drsSource);
                            drsDate = Convert.ToDateTime(dr[row]["Dates"]).ToString("yyyy/MM/dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
                            calendar.AddChildAsCalendar("1" + drsSource + DateTime.Now.ToString("yyyyMMddHHmmssfff",DateTimeFormatInfo.InvariantInfo));
                            calendarNew = calendar.get_ChildAsCalendar(calendar.ChildCount);
                            calendarNew.set_Resource(0, resource);
                            calNewDate = new ASVDateExpressionClass();
                            calendarNew.SetAsStr((TPropertyID)1017, 1, drsDate);
                            //calNewDate.SetStr(drsDate);
                            //calendarNew.set_Date(0, calNewDate);
                            calendarNew.set_ShiftCode(0, dr[row]["ShiftCode"].ToString());

                            //更新资源量
                            calendarNew.DefaultQty =Convert.ToDouble( dr[row]["DefaultQty"]);

                            //更新优先度
                            calendarNew.SortOrder =Convert.ToInt32( Convert.ToDouble(dr[row]["SortOrder"]));

                            //更新备注信息
                            calendarNew.set_Comment(0, "ERP导入(" + DateTime.Now.ToString("yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo) + ")");

                            //设定实际人数
                            calendarNew.SetAsStr((TPropertyID)Convert.ToInt32(common.GetLanguageWord("PropertyID", "CalendarUser_UMans")), 1, dr[row]["CalendarUser_UMans"].ToString());
                            common.pro.UpdateAll();

                        }

                    }
                   
                    
                    
                }


                DevExpress.XtraEditors.XtraMessageBox.Show("所选数据已成功导入到Asporva中!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
        
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                //写入更新标志,已导入Asprova标志及日志
                //string strInsertLog = " set xact_abort on begin tran "
                //                    + " insert into OpLog values('" + strTranNo
                //                    + "','Order Import'," + importFlag.ToString()
                //                    + ",'" + recCount.ToString() + "','" 
                //                    + remark + "','"
                //                    + common._userid
                //                    + "',getdate(),1) "

                //                    + "  commit tran ";
                //accessdb.RsChange(strInsertLog); 

                Cursor.Current = currentCursor;
            }
           
        }

        private bool CheckReSource(DataRow[] drs)
        {
            bool flag = false;

            for (int i = 0; i < drs.Length; i++)
            {
                flag = false;
                for (int j = 0; j < common.pro.RootResource.ChildCount; j++)
                {

                    if (common.pro.RootResource.get_ChildAsResource(j).Code == drs[i]["ResourceCode"].ToString())
                    {

                        flag = true;
                        break;
                    }
                }
                if (!flag)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("表格数据中的资源编号在Asprova中不存在，请检查!\r\n" 
                                                                + "资源编号:" + drs[i]["ResourceCode"].ToString(), 
                                                                common.sysParameter.MessageInf, MessageBoxButtons.OK,
                                                                MessageBoxIcon.Information);
                    return false;
                }
            }
            return true;
        }

        //切换用户
        private void txtChange_Click(object sender, EventArgs e)
        {
            frmLogon frmLog = new frmLogon();
            frmLog.ShowDialog();

            if (frmLog.DialogResult == DialogResult.OK)
            {
                IniDataSource();
            }

            frmLog.Dispose();
            frmLog = null;
        }

        private void frmCalendarImport_FormClosing(object sender, FormClosingEventArgs e)
        {
            serial.SerializeBinary(common.sysParameter, Application.StartupPath + @"\NNLInterface.dat");
            common._its_accessdb = null;
            common.pro = null;
            GC.Collect();
        }
    }
}
